#!/usr/bin/env python
# coding=utf-8
# 修改pasa update的 gff文件
# 将mRNA1.1这种 改为 mRNA1

import re

import argparse
import sys


parser = argparse.ArgumentParser(
    description='''将pasa update的结果转化中的 mRNA1.1 替换为 mRNA2
    这个脚本是在用pasa update完之前改过的evm结果的基础上用的 mRNA的命名必须是 xxx.mRNA(n) n 为数字
    用法:
    pasagff_modified.py -i nig_pb_trans01.gene_structures_post_PASA_updates.1644587.gff3 -o nig_ont_pasa_update.gff3
    由大天才于2021年7月12日创建于浙江农业大学''')

parser.add_argument('-i',
                help='必须给定，输入的gff3文件 ')


parser.add_argument('-o',
                help='必须给定，输出文件')



args = parser.parse_args()

if not args.i or not args.o:
    parser.print_help()
    sys.exit()



infile = args.i

outfile= args.o

# infile = 'nig_pb_trans01.gene_structures_post_PASA_updates.1644587.gff3'

# outfile = r'nig_ont_pasa_update.gff3'




item_property_pattern = re.compile(r'([^=|^;]+)=([^;]+)')

item_mRNA_pattern = re.compile(r'mRNA(\d+)')


name = ''
outhandel = open(outfile,'w')

outhandel.write('##gff-version 3\n')

with open(infile) as fila:
	for i in fila:
		k = i.strip().split('#')[0].split('\t')

		if len(k) >= 8:

			item_dic = {i[0]:i[1] for i in item_property_pattern.findall(k[8])}

			if k[2] == 'mRNA':

				cdsn = 1
				
				mRNA_number_lista = item_mRNA_pattern.findall(item_dic['ID'])

				if mRNA_number_lista!=[] and mRNA_number_lista[0].isdigit():
					base_number = int(mRNA_number_lista[0])

			

				if item_dic['ID'].split('.')[-1].find('mRNA')==-1:

					number = str(int(item_dic['ID'].split('.')[-2])+base_number)

					name = '.'.join(item_dic['ID'].split('.')[:-3])+'.mRNA' + number

					k[8] = ('ID=%s;Name=%s;Parent=%s;' % (name, name, item_dic['Parent']))

				else:
					name = item_dic['ID']

					k[8] = ('ID=%s;Name=%s;Parent=%s;' % (name, name, item_dic['Parent']))

				

			if k[2] in ['exon', 'five_prime_UTR','three_prime_UTR'] and name !='':
				exon_number = item_dic['ID'].split('.')[-1]
				exon_name = name+'.'+exon_number

				


				k[8] = ('ID=%s;Name=%s;Parent=%s;' % (exon_name, exon_name, name))


			elif k[2]=='CDS' and name !='':
			

				exon_name = name+'.CDS'+str(cdsn)

				cdsn += 1

				k[8] = ('ID=%s;Name=%s;Parent=%s;' % (exon_name, exon_name, name))


			if k[2] not in ['gene','mRNA','CDS','exon','five_prime_UTR','three_prime_UTR']:
				continue
			else:
				outhandel.write('\t'.join(k)+'\n')

outhandel.close()

				# cds_or_exon_name = 
				# item[8] = ('ID=%S;Name=%s;Parent%s;' % (name, name, item_dic['Parent']))



			
